from datetime import datetime, timedelta
from collections import defaultdict
from fastapi import HTTPException
from config.settings import settings

class RateLimiter:
    def __init__(self):
        self.request_counts = defaultdict(list)
    
    async def check_rate_limit(self, client_ip: str) -> bool:
        """检查请求速率限制"""
        now = datetime.now()
        window_start = now - timedelta(seconds=settings.RATE_WINDOW)
        
        # 清理过期的请求记录
        self.request_counts[client_ip] = [
            t for t in self.request_counts[client_ip] 
            if t > window_start
        ]
        
        # 检查是否超过限制
        if len(self.request_counts[client_ip]) >= settings.RATE_LIMIT:
            raise HTTPException(
                status_code=429,
                detail=f"请求过于频繁，请稍后再试（限制：{settings.RATE_LIMIT}次/分钟）"
            )
        
        self.request_counts[client_ip].append(now)
        return True

# 创建全局实例
rate_limiter = RateLimiter() 